<!-- 部门管理 部门列表组件 -->
<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item> -->
      <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>字典管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <!-- <el-form-item label="字典名称" prop="dictValue">
          <el-input v-model="queryInfo.dictValue" placeholder="请输入字典名称" clearable />
        </el-form-item> -->
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="queryInfo.dictLabel" placeholder="请输入字典标签" clearable />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryInfo.status" placeholder="状态" clearable style="width: 240px">
            <el-option label="正常" value="0">正常</el-option>
            <el-option label="停用" value="1">停用</el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="handleQuery" type="primary" icon="el-icon-search" size="mini">搜索</el-button>
          <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 按钮区域 -->
      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTypeHandle">新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini">删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini">导出</el-button>
        </el-col> -->
        <el-col :span="1.5">
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-close" size="mini" @click="closeViewHandler">返回</el-button>
        </el-col>
        <!-- right-toolbar  百度:显示/隐藏列操作按钮-->
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%;margin-bottom: 20px;" row-key="id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="dictId" label="字典编号">
        </el-table-column>
        <el-table-column prop="dictLabel" label="字典标签">
        </el-table-column>
        <el-table-column prop="dictValue" label="字典键值">
        </el-table-column>
        <el-table-column prop="dictSort" label="字典排序">
        </el-table-column>
        <el-table-column prop="remark" label="备注">
        </el-table-column>
         <el-table-column prop="isDefault" label="默认选中">
            <template slot-scope="scope">
              <span :value="scope.row.isDefault">{{ scope.row.isDefault === 'Y' ? '是' : '否' }}</span>
            </template>
          </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span :value="scope.row.status">{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="updateData(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="deleteData(scope.row.dictId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加字典数据 弹窗 -->
    <el-dialog :title="upload.title" width="460px" :visible.sync="dialogVisible" @close="addDialogClosed">
      <!-- 内容主题区域 -->
      <el-form ref="addFormRef" :model="addForm" label-width="70px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="字典类型" prop="dictType">
              <el-input v-model="addForm.dictType" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据标签" prop="dictLabel">
              <el-input v-model="addForm.dictLabel"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据键值" prop="dictValue">
              <el-input v-model="addForm.dictValue"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="样式属性" prop="cssClass">
              <el-input v-model="addForm.cssClass"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="dictSort">
              <el-input-number v-model="addForm.dictSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="回显样式" prop="listClass">
              <el-select v-model="addForm.listClass" placeholder="请选择">
                <el-option v-for="item in listClassOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="24">
              <el-form-item label="默认选中" prop="isDefault">
                <el-radio-group v-model="addForm.isDefault">
                  <el-radio label="Y">是</el-radio>
                  <el-radio label="N">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="addForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
                v-model="addForm.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    // 验证邮箱的规则 自定义校验规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱!'))
    }
    // 验证手机的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的规则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号!'))

    }
    return {
      showSearch: true,
      // 数据标签回显样式
      listClassOptions: [
        {
          value: 'default',
          label: '默认'
        },
        {
          value: 'primary',
          label: '主要'
        },
        {
          value: 'success',
          label: '成功'
        },
        {
          value: 'info',
          label: '信息'
        },
        {
          value: 'warning',
          label: '警告'
        },
        {
          value: 'danger',
          label: '危险'
        }
      ],
      // 获取用户列表数据的参数对象
      queryInfo: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        dictLabel: undefined,
        dictValue: undefined, // 字典键值
        status: undefined,
      },
      userList: [],
      total: 0,
      // 对话框显示与隐藏
      dialogVisible: false,
      dicId: undefined,
      // 添加用户的表单数据
      addForm: {
        isDefault: 'Y',
        dictType: this.$route.query.dictType,
        status: '0',
        dictLabel: undefined,
        dictSort: 0,
        dictValue: undefined,
        cssClass: undefined,
        listClass: '默认',
        remark: '',
        dictCode: undefined
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
      },
      // 添加表单验证的校验规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名!', trigger: 'blur', },
          { min: 3, max: 12, message: '用户名的长度在3~12个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码!', trigger: 'blur', },
          { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱!', trigger: 'blur', },
          { validator: checkEmail, trigger: 'blur', }
        ],
        mobile: [
          { required: true, message: '请输入手机号!', trigger: 'blur', },
          { validator: checkMobile, trigger: 'blur', }
        ],
      },
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
  */
  created() {
    this.getList()
    // this.handleSizeChange()
    // this.handleCurrentChange()
  },
  /**
  * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
  */
  mounted() { },
  // 组件方法
  methods: {
    // 字典数据列表
    async getList() {
        this.queryInfo.dictType = this.$route.query.dictType
        const params = this.queryInfo
        const { data: res } = await this.$http.post('/sys-dict-type/pageDict', params)
        if (res.code === 20000) {
          this.userList = res.data.records
          this.addForm.dictCode = res.data.records.dictCode
          this.total = parseInt(res.data.total)
        } else {
          this.$message.error(res.msg)
        }
    },
    // 新增 弹窗
    addTypeHandle() {
      this.dialogVisible = true
      this.upload.title = "添加字典数据"
      console.log(1);
    },
    // 修改按钮操作
    updateData(row) {
      const dictId = row.dictId
      console.log(dictId);
      this.dicId = row.dictId
      this.dialogVisible = true
      this.upload.title = "修改字典数据"
      this.addForm = row
    },
    // 删除 
    // async deleteData(row) {
    //   const { data: res } = await this.$http.post('/sys-dict-type/deleteDict', [row])
    //   console.log(res);
    //   if (res.code === 20000) {
    //     this.getList()
    //     return this.$message.success('删除成功')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
     // 删除弹窗封装
    async deleteData(row) {
      if (!(await this._box(row, 'post', '/sys-dict-type/deleteDict'))) return;
    },
    // 提交按钮 添加修改类型
    addUser() {
      this.$refs['addFormRef'].validate(async valid => {
        if (valid) {
          console.log(this.addForm.dictId);
          if (this.addForm.dictId != undefined) {
            console.log(this.addForm.dictId, '修改');
            const params = this.addForm
            const { data: res } = await this.$http.post('/sys-dict-type/updateDict', params)
            console.log(res);
            if (res.code === 20000) {
              this.$message.success(`修改成功!`)
              this.getList()
              this.dialogVisible = false
            } else {
              this.$message.error(res.msg)
            }
          } else {
            const params = this.addForm
            const { data: res } = await this.$http.post('/sys-dict-type/addDict', params)
            if (res.code === 20000) {
              this.$message.success(`新增成功!`)
              this.getList()
              this.dialogVisible = false
              this.$refs['addFormRef'].resetFields()
            } else {
              this.$message.error(res.msg)
              this.$refs['addFormRef'].resetFields()
            }
          }
        }
      })
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getList()
    },
    // 关闭 返回到 定时任务页面
    closeViewHandler() {
      this.$router.push('/dict')
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs['addFormRef'].resetFields()
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryInfo.currentPage = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      // this.resetForm('queryForm')
      // console.log(this) this指向$refs的是通过ref获得的实例对象loginFormRef
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
  }
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
